package com.longbo.leaf.security;

import com.longbo.leaf.common.Status;
import com.longbo.leaf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;



@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired(required = false)
    private AccessDeniedHandler accessDeniedHandler;

    /**
     * 密码加密器
     * @return
     */
    @Bean
    public PasswordEncoder encoder(){
       return new BCryptPasswordEncoder();
    }

    /**
     * 访问被拒绝返回的字符串提醒
     * @return
     */
    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        return (request, response,  e) -> ResponseUtil.renderJson(response, Status.ACCESS_DENIED,null);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        "/cdn.jsdliver.net/**",
//                "/cdn.staticfile.org/**",
        // 登录页面
        String loginPageUrl = "/login.html";
        // 处理登录的URL，即登录表单提交到哪里去
        String loginProcessingUrl = "/login";
        // 不需要登录即可访问的URL
        String[] urls = {
                loginPageUrl,
                loginProcessingUrl,
                "/favicon.ico",
                "/browser_components/**",
                "/css/**",
                "/img/**",
                "/js/**",

                "/npm/**",
                "/register.html",
                "/api/user/selectUserAll"
        };

        http.sessionManagement().maximumSessions(1);
        http.authorizeRequests()
                .antMatchers(urls).permitAll()
                .anyRequest().authenticated();
              http.formLogin().loginPage(loginPageUrl).loginProcessingUrl(loginProcessingUrl).defaultSuccessUrl("/index.html")
               .and()
               .logout().logoutUrl("/logout").logoutSuccessUrl("/login.html");

               //认证请求

               //所有请求都要登录访问


//               // 登出行为由自己实现，参考 AuthController#logout
//               .and().logout().disable()
//
//               //session管理
//               .sessionManagement()
//               // 因为使用了JWT，所以这里不管理Session
//               .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//
//               .and().exceptionHandling().accessDeniedHandler(accessDeniedHandler);

      http.csrf().disable();

    }
}
